<template>
  <Container class="tyre-list">
    <div slot="header" class="container-header large">
      <Form class="search">
        <Row>
          <i-col span="5">
            <FormItem label="科室">
              <Select v-model="form.officeId" clearable filterable @on-change="setDepartment">
                <Option v-for="(item, index) of reportDepart" :key="index" :value="item">{{ item.name }}</Option>
              </Select>
            </FormItem>
            <FormItem label="选择门店">
              <SelectStore v-model="form.storeId" @input="onSearchBtnClick" />
            </FormItem>
          </i-col>
          <i-col span="5">
            <FormItem label="部门">
              <Select v-model="form.departmentId" clearable filterable @on-change="setDistribute">
                <Option v-for="(item, index) of departments" :key="index" :value="item.id">{{ item.name }}</Option>
              </Select>
            </FormItem>
            <FormItem v-if="tab === 'tab1'" label="兑换礼品">
              <Select v-model="form.prizeId" multiple clearable placeholder="请选择礼品">
                <Option v-for="(item,index) in prizes" :key="index" :value="item.id">
                  {{ item.label }}
                </Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem label="经销商">
              <Select v-model="form.distributorId" multiple clearable @on-change="getData">
                <Option v-for="(item, index) of distributors" :key="index" :value="item.distributorId">{{ item.distributorName }}</Option>
              </Select>
            </FormItem>
            <FormItem v-if="tab === 'tab1'" label="收货地址">
              <Input v-model.trim="form.receiverInfo" placeholder="请输入收货地址" @on-enter="onSearchBtnClick" />
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem label="门店类型">
              <Select v-model="form.storeType" filterable clearable @on-change="getData">
                <Option v-for="(item, index) of storeTypes" :key="index" :value="item.id">{{ item.label }}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col class-name="search" span="2">
            <Button class="btn-search large" type="primary" icon="ios-search" @click="onSearchBtnClick" />
          </i-col>
        </Row>
      </Form>
    </div>
    <Tabs v-model="tab">
      <Button v-if="tab === 'tab1'" slot="extra" size="large" class="item" type="primary" @click="onImport">导入快递单号</Button>
      <export-btn slot="extra" :param="exportParam" :url="exportUrl" :methods="exportMethod" class="item" />
      <TabPane label="门店兑换统计" name="tab1">
        <homeTable :list="list" @getData="getData" @onPageSizeChange="onPageSizeChange" @onPageChange="onPageChange" />
      </TabPane>
      <TabPane label="门店数据统计" name="tab2">
        <homeTable :list="list" @getData="getData" @onPageSizeChange="onPageSizeChange" @onPageChange="onPageChange" />
      </TabPane>
    </Tabs>
    <ExpressOrder ref="express" />
    <Import ref="import" title="导入快递单号" template-url="trackingNo.xlsx" url="/api/taiyi/report/purch_exchange_record/import" @complete="getData" />
    <giftDetailItem ref="goods" />
    <StoreDataItem ref="store" />
  </Container>
</template>
<script>
import homeTable from '~/homeTable'
import SelectStore from '~/SelectStore'
import storeExchangeData from './list/storeExchangeListData'
import storeDetailListData from './list/storeDetailListData.js'
import ExpressOrder from '@/components/ExpressOrderItem'
import Import from '@/components/Import'
import StoreDataItem from './list/StoreDataItem'
import giftDetailItem from './list/giftDetailItem'
import { clearEmpty } from '@/util'
import { mapGetters } from 'vuex'
export default {
  name: 'product/manage/list',
  components: {
    homeTable,
    SelectStore,
    ExpressOrder,
    Import,
    StoreDataItem,
    giftDetailItem
  },
  data () {
    return {
      tab: this.$route.query.tab || 'tab1',
      list: storeExchangeData,
      form: {
        storeId: null,
        officeId: {},
        departmentId: null,
        distributorId: [],
        receiverInfo: '',
        prizeId: null,
        storeType: null
      },
      departments: [],
      prizes: [],
      distributors: [],
      storeTypes: [],
      giftType: 2
    }
  },
  computed: {
    ...mapGetters(['reportDepart']),
    exportParam () {
      let param = {
        current: this.list.currentPage,
        size: this.list.pageSize,
        storeId: this.form.storeId,
        officeId: (this.form.officeId && Object.keys(this.form.officeId).length > 0) ? this.form.officeId.id : null,
        departmentId: this.form.departmentId,
        distributorIds: this.form.distributorId,
        giftType: 2,
        storeTypeId: this.form.storeType
      }
      if (this.tab === 'tab1') {
        param.prizeIds = this.form.prizeId
        param.receiverInfo = this.form.receiverInfo
      }
      param = clearEmpty(param)
      return param
    },
    exportUrl () {
      return this.tab === 'tab1' ? '/report/purch_exchange_record/export' : '/report/purch_gift_statistics/export'
    },
    exportMethod () {
      return  'POST'
    }
  },
  watch: {
    tab: {
      handler (newVal) {
        if (newVal === 'tab1') {
          this.list = storeExchangeData
        } else {
          this.list = storeDetailListData
        }
        const { currentPage = 1, pageSize = 20 } = this.list
        this.$router.push({
          name: 'home/tyreApril/list',
          query: {
            currentPage: currentPage,
            pageSize: pageSize,
            tab: newVal
          }
        })
        this.getData()
      },
      immediate: true
    }
  },
  mounted () {
    storeExchangeData.currentPage = ~~this.$route.query.currentPage || 1
    storeExchangeData.pageSize = ~~this.$route.query.pageSize || storeExchangeData.pageSize
    storeDetailListData.currentPage = ~~this.$route.query.currentPage || 1
    storeDetailListData.pageSize = ~~this.$route.query.pageSize || storeDetailListData.pageSize
    this.$store.dispatch('getListDepartmentTree')
    this.getPrize()
    this.getData()
    this.getStoreType()
    this.$bus.$on('express', this.onCheckTrack)
    this.$bus.$on('onCheck', this.onCheckStore)
    this.$bus.$on('onViewGoodsDetail', this.onViewGoodsDetail)
  },
  destroyed () {
    this.$bus.$off('express')
    this.$bus.$off('onCheck')
    this.$bus.$off('onViewGoodsDetail')
  },
  methods: {
    onSearchBtnClick () {
      this.list.currentPage = 1
      this.getData()
    },
    getData () {
      this.list.status = 'loading'
      let param = {
        ...this.exportParam,
        current: this.list.currentPage,
        size: this.list.pageSize
      }
      const url = this.tab === 'tab1' ? '/report/purch_exchange_record/page' : '/report/purch_gift_statistics/page'
      if (this.tab === 'tab1') {
        this.$jsonPost(url, param).then(data => {
          this.list.totalItem = Number(data.total)
          this.list.data = data.records || []
          this.list.status = 'pass'
        }).catch(() => {
          this.list.status = 'error'
        })
      } else {
        this.$ajaxGet(url, param).then(data => {
          this.list.totalItem = Number(data.total)
          this.list.data = data.records || []
          this.list.status = 'pass'
        }).catch(() => {
          this.list.status = 'error'
        })
      }
    },
    setDepartment (row) {
      if (!row) {
        this.form.officeId = {}
        this.form.departmentId = null
        this.departments = []
        this.form.distributorIds = []
        this.distributors = []
      } else {
        this.departments = row.children
      }
    },
    setDistribute (id) {
      this.form.distributorIds = []
      if (id) {
        this.$store.dispatch('getDistributorDepartment', { departId: id }).then(res => {
          this.distributors = res
        })
      } else {
        this.distributors = []
      }
    },
    getPrize () {
      this.$ajaxGet('/report/purch_exchange_record/prize_list/APR_MAY_PURCH_ACTIVITY').then(data => {
        this.prizes = (data || []).map(item => {
          return {
            id: item.giftId,
            label: item.giftName
          }
        })
      })
    },
    getStoreType () {
      this.$ajaxGet('/report/purch_exchange_record/store_type_map/APR_MAY_PURCH_ACTIVITY').then(data => {
        this.storeTypes = []
        for (let [key, value] of Object.entries(data)) {
          this.storeTypes.push({
            id: key,
            label: value
          })
        }
      })
    },
    onCheckTrack (num) {
      this.$refs.express.updateInfo(num)
    },
    onCheckStore (id) {
      this.$refs.store.getInfo(id, 'APR_MAY_PURCH_ACTIVITY')
    },
    onViewGoodsDetail ({ id, type, month, year }) {
      this.$refs.goods.getInfo(id, type, this.giftType, month, year)
    },
    onImport () {
      this.$refs.import.reset()
    },
    onPageChange (number) {
      this.list.currentPage = number
      this.$router.push({
        name: 'home/tyreApril/list',
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize,
          tab: this.tab
        }
      })
      this.getData()
    },
    onPageSizeChange (pageSize) {
      this.list.currentPage = 1
      this.list.pageSize = pageSize
      this.$router.push({
        name: 'home/tyreApril/list',
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize,
          tab: this.tab
        }
      })
      this.getData()
    }
  }

}
</script>
